package com.jpragma.blazeds.utils;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Serves resources from server classpath. Note that appropriate mapping must be configured in web.xml
 * @author Isaac Levin
 */
public class ClasspathResourceServlet extends HttpServlet {
	private static final int BUFFER_LENGTH = 1024;
	
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String resourcePath = request.getServletPath() + request.getPathInfo();
		
		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
		InputStream is = classLoader.getResourceAsStream(resourcePath);
		if (is != null) {
			ServletOutputStream outputStream = response.getOutputStream();
			int bytesRead;
			do {
				byte[] buffer = new byte[BUFFER_LENGTH];
				bytesRead = is.read(buffer);
				if (bytesRead > 0) {
					outputStream.write(buffer, 0, bytesRead);
				}
			} while (bytesRead > 0);
			outputStream.flush();
		} else {
			response.sendError(404);
		}
	}
}
